"""
应用配置
"""

import os
from functools import lru_cache
from typing import Any, Dict, Optional

from pydantic import validator
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """应用设置"""

    # 应用基本配置
    app_name: str = "Tete1 Git同步系统"
    app_version: str = "1.0.0"
    debug: bool = False
    secret_key: str

    # 数据库配置
    database_url: str
    database_echo: bool = False

    # Redis配置
    redis_url: str
    celery_broker_url: str
    celery_result_backend: str

    # 任务执行配置
    max_workers: int = 4
    default_task_timeout: int = 3600
    max_concurrent_tasks: int = 5
    default_retry_count: int = 3

    # 文件存储配置
    upload_dir: str = "/app/files"
    log_dir: str = "/app/logs"
    repo_cache_dir: str = "/app/repos"
    max_file_size: int = 100 * 1024 * 1024  # 100MB

    # 日志配置
    log_level: str = "INFO"
    log_retention_days: int = 30
    max_log_size_mb: int = 100

    # 邮件配置
    smtp_host: Optional[str] = None
    smtp_port: int = 587
    smtp_username: Optional[str] = None
    smtp_password: Optional[str] = None
    smtp_use_tls: bool = True
    email_from: Optional[str] = None

    # 安全配置
    allowed_hosts: list[str] = ["*"]
    cors_origins: list[str] = ["http://localhost:3000", "http://192.168.*"]

    # API配置
    api_prefix: str = "/api/v1"
    docs_url: str = "/docs"
    redoc_url: str = "/redoc"

    # 监控配置
    enable_metrics: bool = True
    metrics_port: int = 9090

    class Config:
        env_file = ".env"
        case_sensitive = False

    @validator("cors_origins", pre=True)
    def assemble_cors_origins(cls, v):
        """处理CORS origins配置"""
        if isinstance(v, str):
            return [i.strip() for i in v.split(",")]
        return v

    @validator("allowed_hosts", pre=True)
    def assemble_allowed_hosts(cls, v):
        """处理允许的主机配置"""
        if isinstance(v, str):
            return [i.strip() for i in v.split(",")]
        return v

    @property
    def is_email_enabled(self) -> bool:
        """检查是否启用邮件功能"""
        return all([self.smtp_host, self.smtp_username, self.smtp_password, self.email_from])

    @property
    def database_config(self) -> Dict[str, Any]:
        """获取数据库配置"""
        return {
            "url": self.database_url,
            "echo": self.database_echo,
            "pool_size": 10,
            "max_overflow": 20,
            "pool_pre_ping": True,
        }

    @property
    def celery_config(self) -> Dict[str, Any]:
        """获取Celery配置"""
        return {
            "broker_url": self.celery_broker_url,
            "result_backend": self.celery_result_backend,
            "task_serializer": "json",
            "accept_content": ["json"],
            "result_serializer": "json",
            "timezone": "UTC",
            "enable_utc": True,
            "task_track_started": True,
            "task_acks_late": True,
            "worker_prefetch_multiplier": 1,
            "worker_max_tasks_per_child": 1000,
        }

    def get_email_config(self) -> Optional[Dict[str, Any]]:
        """获取邮件配置"""
        if not self.is_email_enabled:
            return None

        return {
            "host": self.smtp_host,
            "port": self.smtp_port,
            "username": self.smtp_username,
            "password": self.smtp_password,
            "use_tls": self.smtp_use_tls,
            "from_address": self.email_from,
        }

    def ensure_directories(self) -> None:
        """确保必要的目录存在"""
        directories = [self.upload_dir, self.log_dir, self.repo_cache_dir]
        for directory in directories:
            os.makedirs(directory, exist_ok=True)


@lru_cache()
def get_settings() -> Settings:
    """获取应用设置（单例模式）"""
    return Settings()


# 全局设置实例
settings = get_settings()